import Qfpage from "../../components/Qfpage/Qfpage";
import React from 'react';
import 'antd/dist/antd.css';
import { Space, Table, Tag, Pagination, Button, Col, DatePicker, Drawer, Form, Input, Row, Select, InputNumber, Popconfirm, message, Modal } from 'antd';
import { getAllType, addType, delType, editType } from '../../api/roomType';
import { useEffect, useState, useMemo, useRef, useLayoutEffect } from 'react';
import './style.scss'

const Room = () => {


    const [data, setData] = useState([]);
    const [limit, setLimit] = useState(10);//每页显示的数据
    const [page, setPage] = useState(1);//页数
    const [total, setTotal] = useState(0); // 总数
    const getData = async () => {
        const postData = { limit,page };
        if(name) postData.name = name;
        let res = await getAllType(postData)
        const {  success ,data, count} = res;
        if(success) {
            setData(data);
            setTotal(count)
        };   

    }
    // 条件过滤
    const [name, setName] = useState('');

    //挂在完成后显示
    useLayoutEffect(()=>{
        getData();
    },[limit,page,name])

    const columns = useMemo(() => [
        {
            title: '房型名称',
            dataIndex: 'name',
            Key: 'name',
        },
        {
            title: '床数量',
            dataIndex: 'beds',
            Key: 'beds',
        },
        {
            title: '价格',
            dataIndex: 'price',
            Key: 'price',
        },
        {
            title: '押金',
            dataIndex: 'yaPrice',
            Key: 'yaPrice',
        },
        {
            title: '简称',
            dataIndex: 'shortName',
            Key: 'shortName',
        },
        {
            title: '入住人数',
            dataIndex: 'liveLimit',
            Key: 'liveLimit',
        }, {
            title: '早餐券',
            dataIndex: 'couponNum',
            Key: 'couponNum',
        }, {
            title: '操作',
            dataIndex: 'operation',
            render: (_, row) =>
                <>
                    <Button onClick={() => handlerDel(row._id)} ghost danger>
                        删除
                    </Button>
                    <Button style={{ marginLeft: '5px' }} onClick={() => openEdit(row)} type="primary" ghost>
                        修改
                    </Button>
                </>




        }

    ], [])



    // 添加房型的操作(抽屉)
    const [visible, setVisible] = useState(false);

    const showDrawer = () => {
        setVisible(true);//显示抽屉
    };

    const onClose = () => {
        setVisible(false);//隐藏抽屉
    };

    const refFrom = useRef(null);//获取表单全部数据
    // 表单的校验规则

    const rules = {
        name: [{ required: true, message: '不可能不填吧', type: 'error' }],
        price: [{ required: true, message: '不可能不填吧', type: 'error' }]
    }
    //************* 添加新房型 **************************************
    const handleAdd = async () => {
        const values = refFrom.current.getFieldsValue(true);
        console.log('values', values)
        let res = await addType(values)
        const { success } = res
        if (!success) return message.warning('添加失败');
        message.success('添加成功')
        getData();// 刷新表格
        onClose();//关闭抽屉
        refFrom.current.resetFields()//表单重置
    }


    // *********************************修改房型的操作*****************************
    const [showEdit, setShowEdit] = useState(false);
    const editRef = useRef(null);
    const [curRow, setCurRow] = useState(null)
    const openEdit = (row) => {
        setCurRow(row)
        // 设置 修改表单的内容
        editRef.current.setFieldsValue(row)
        setShowEdit(true); //  让修改抽屉弹出
    }
    const handleEdit = async () => {
        const values = editRef.current.getFieldsValue(true); // 得到所有的表单的值
        // 发送请求执行修改
        let res = await editType({
            ...values,
            typeid: curRow._id
        });
        const { success } = res;
        if (!success) return message.warning('修改失败');
        message.success('修改成功');
        getData(); // 刷新表格
        setShowEdit(false) // 抽屉隐藏
    }

    // **********************删除房型**********************************************
    const confirmDel = async (id) => {
        let res = await delType({ typeid: id });
        const { success } = res;
        if (!success) return message.warning('删除失败')
        message.success('删除成功');
        getData();
    }

    const { confirm } = Modal;
    const destroyAll = () => {
        Modal.destroyAll();
    };
    const handlerDel = (id) => {
        confirm({
            content: <Button onClick={destroyAll}>确定要删除吗？</Button>,
            onOk() {
                console.log('OK');
                confirmDel(id)
            },
            onCancel() {
                console.log('Cancel');
            },
        });


    };
    // ***********************************搜索框***********************************



    return (
        <Qfpage title="设置">
            <div>房型维护</div>
            <div>
                <Button type="primary" style={{ marginTop: '10px' }} onClick={showDrawer}>添加房型</Button>
                <div style={{ marginLeft: '60%',display:"flex"}}>
                <Input.Group>
                    <Input 
                    placeholder="输入你有查询的房型" 
                    allowClear
                    onChange={(ev) => {
                            setName(ev.target.value) 
                        }}  /> 
                </Input.Group>
                <Button 
                onClick={getData }
                type="primary">立即查询</Button>
                </div>
            </div>
            <Table
                columns={columns}
                dataSource={data}
                Pagination={{
                    defaultPageSize: limit,
                    total:{total},
                    onChange({ pageSize, current }) {
                        setPage(current);
                        setLimit(pageSize)

                    }
                }}
            />

            {/* 增加房型的抽屉 */}
            <Drawer
                width={500}
                onClose={onClose}
                visible={visible}
                bodyStyle={{
                    paddingBottom: 80,
                }}
            >
                <Form layout="vertical"
                    ref={refFrom}
                    rules={rules}>
                    <Popconfirm
                        icon={null}
                        onConfirm={handleAdd}
                        onCancel={onClose}
                        okText="添加"
                        cancelText="取消"
                    >
                        <Button type="primary">是否确定添加</Button>
                    </Popconfirm>
                    <Form.Item
                        name="name"
                        label="房型"
                        rules={[
                            {
                                required: true,
                                message: '填写房型名称',
                            },
                        ]}
                    >
                        <Input placeholder="填写房型名称" />
                    </Form.Item>
                    <Form.Item
                        name="shortName"
                        label="房型简称"
                        rules={[
                            {
                                required: true,
                                message: '填写房间简称',
                            },
                        ]}
                    >
                        <Input placeholder="填写房间简称" />
                    </Form.Item>
                    <Form.Item
                        name='beds'
                        label="床数"
                    >
                        <InputNumber min={1} max={4} />
                    </Form.Item>
                    <Form.Item
                        name='liveLimit'
                        label="入住人数"
                    >
                        <InputNumber min={1} max={4} />
                    </Form.Item>
                    <Form.Item
                        name='couponNum'
                        label="早餐券数量"
                    >
                        <InputNumber min={1} max={4} />
                    </Form.Item>
                    <Form.Item
                        name="price"
                        label="价格"
                        rules={[
                            {
                                required: true,
                                message: '填写价格',
                            },
                        ]}
                    >
                        <Input placeholder="填写价格" />
                    </Form.Item>
                    <Form.Item
                        name="yaPrice"
                        label="押金"
                        rules={[
                            {
                                required: true,
                                message: '填写押金',
                            },
                        ]}
                    >
                        <Input placeholder="填写押金" />
                    </Form.Item>

                </Form>

            </Drawer>

            {/* 修改房型的抽屉 */}
            <Drawer
                forceRender={true}
                width={500}
                closable={false}
                onClose={onClose}
                visible={showEdit}
                bodyStyle={{
                    paddingBottom: 80,
                }}
            >
                <Form layout="vertical"
                    ref={editRef}
                    rules={rules}>
                    <Popconfirm
                        icon={null}
                        onConfirm={handleEdit}
                        onCancel={() => setShowEdit(false)}
                        okText="修改"
                        cancelText="取消"
                    >
                        <Button type="primary">是否确定修改</Button>
                    </Popconfirm>
                    <Form.Item
                        name="name"
                        label="房型"
                        rules={[
                            {
                                required: true,
                                message: '填写房型名称',
                            },
                        ]}
                    >
                        <Input placeholder="填写房型名称" />
                    </Form.Item>
                    <Form.Item
                        name="shortName"
                        label="房型简称"
                        rules={[
                            {
                                required: true,
                                message: '填写房间简称',
                            },
                        ]}
                    >
                        <Input placeholder="填写房间简称" />
                    </Form.Item>
                    <Form.Item
                        name='beds'
                        label="床数"
                    >
                        <InputNumber min={1} max={4} />
                    </Form.Item>
                    <Form.Item
                        name='liveLimit'
                        label="入住人数"
                    >
                        <InputNumber min={1} max={4} />
                    </Form.Item>
                    <Form.Item
                        name='couponNum'
                        label="早餐券数量"
                    >
                        <InputNumber min={1} max={4} />
                    </Form.Item>
                    <Form.Item
                        name="price"
                        label="价格"
                        rules={[
                            {
                                required: true,
                                message: '填写价格',
                            },
                        ]}
                    >
                        <Input placeholder="填写价格" />
                    </Form.Item>
                    <Form.Item
                        name="yaPrice"
                        label="押金"
                        rules={[
                            {
                                required: true,
                                message: '填写押金',
                            },
                        ]}
                    >
                        <Input placeholder="填写押金" />
                    </Form.Item>

                </Form>

            </Drawer>
        </Qfpage>
    )
}

export default Room